from flask import Flask, request, jsonify, send_from_directory
import os
import startcode
import sys

app = Flask(__name__)
# 创建一个文件夹invideo，用来存放用户上传的视频
app.config['INVIDEO_FOLDER'] = 'invideo'
if not os.path.exists(app.config['INVIDEO_FOLDER']):
    os.makedirs(app.config['INVIDEO_FOLDER'])

# 访问根目录时，调用index()函数
@app.route('/')
def index():
    return send_from_directory('.', 'index.html')
print("位置一")

# 当有POST请求时，执行upload_video
@app.route('/invideo', methods=['POST'])

def upload_video():
    print("位置2")
    # 如果video为空
    if 'video' not in request.files:
        return jsonify({'error': '没有视频被上传'}), 400
    
    # 获取网页上传的视频
    video = request.files['video']
    # 获取网页上传的side
    side = request.form.get('side', type=int)
    # 获取网页上传的真实身高
    height_real = request.form.get('height', type=int)

    if not video:
        return jsonify({'error': '没有视频被上传'}), 400

    if video.filename == '':
        return jsonify({'error': '没有选择视频文件'}), 400
    
    print("视频文件有效，准备保存")

    if video:
        # 将服务器invideo文件夹与视频文件名组合   **invideo/video.filename   invideo/视频文件名
        video_path = os.path.join(app.config['INVIDEO_FOLDER'], video.filename)
        # video_path = os.path.join(app.config['INVIDEO_FOLDER'], video.filename)
        # print(video_path)
        # print(video.filename)
        # 将用户上传的视频保存到invideo文件夹中
        video.save(video_path)
        # print(type(video))
        
        print("视频已保存，准备调用 startcode函数")

        # 调用startcode，执行后端算法
        startcode.startcode(video_path, side, height_real)
        
        return jsonify({'message': '运行已经完成。'})
    # sys.exit()
        # return True
    # else:
    #     return jsonify({'error': '没有视频被上传'}), 400

if __name__ == '__main__':
    host_address = '127.0.0.1'  # 监听本地请求
    # 使用4090端口
    host_port = 5000
    print(f"访问本地服务器地址: http://{host_address}:{host_port}")
    # 运行app应用
    app.run(debug=True, host=host_address, port=host_port)